<template>

    <div style="display: flex; justify-content: space-between; align-items: center; margin-bottom: 5px;">
    <el-button type="primary" @click="isEditable = !isEditable">
        {{ isEditable ? '锁定' : '编辑' }}
    </el-button>
    <el-button type="text" :disabled="!isEditable" @click="addMenus" >
        <el-icon><Plus /></el-icon>
        新增菜单
    </el-button>
    </div>  
    <el-table
        :data="menusData"
        style="width: 100%"
        row-key="id"
        border
        clearable
        :tree-props="{ children: 'children', hasChildren: 'hasChildren'}"
    >
        <el-table-column prop="name" label="菜单名称" />
        <el-table-column prop="parentId" label="上级菜单" />
        <el-table-column prop="path" label="菜单路径" />
        <el-table-column prop="icon" label="菜单图标" />
        <el-table-column prop="isShow" label="是否显示" :formatter="formatIsShow"/>
        <el-table-column prop="component" label="组件路径"/>
        <el-table-column prop="createdAt" label="创建时间" />
        <el-table-column prop="updatedAt" label="更新时间" />
        <el-table-column label="操作" width="160" align="center">
        <template #default="scope">
            <el-button
            type="primary"
            :icon="Edit"
            size="small"
            :disabled="!isEditable"
            @click="openEditDialog(scope.row)"
            title="编辑部门"
            >编辑</el-button>
            <el-button
            type="danger"
            :icon="Edit"
            size="small"
            :disabled="!isEditable"
            @click="removeMenus(scope.row)"
            title="删除菜单"
            >删除</el-button>
        </template>
        </el-table-column>
  </el-table>
    <el-dialog v-model="dialogFormVisible" title="新增菜单" width="500px">
      <el-form :model="form" :rules="rules" ref="formRef" label-width="100px">
        
        <el-form-item label="菜单名称" prop="name">
          <el-input v-model="form.name" placeholder="请输菜单名称" />
        </el-form-item>
        <el-form-item label="上级菜单" prop="parentId">
          <el-tree-select
            v-model="form.parentId"
            :data="rootType"
            check-strictly
            :props="{ label: 'name', value: 'id', children: 'children'}"
            clearable
            placeholder="请选择父分类（可不选）"
          />
        </el-form-item>
        <el-form-item label="菜单路径" prop="path">
          <el-input v-model="form.path" placeholder="请输菜单路径" />
        </el-form-item>
        <el-form-item label="菜单图标" prop="icon">
          <el-input v-model="form.icon" placeholder="请输菜单图标" />
        </el-form-item>
        <el-form-item label="是否显示" prop="isShow">
          <el-select v-model="form.isShow" placeholder="请选择">
            <el-option label="显示" :value="0"></el-option>
            <el-option label="隐藏" :value="1"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="组件路径" prop="component">
          <el-input v-model="form.component" placeholder="请输组件路径" />
        </el-form-item>
        
      </el-form>

      <template #footer>
        <el-button @click="dialogFormVisible = false">取消</el-button>
        <el-button type="primary" @click="submitForm">确定</el-button>
      </template>
    </el-dialog>
    <el-dialog
    v-model="dialogEditVisible"
    :title="修改菜单"
    width="500px"
    >
    <el-form :model="form" label-width="80px" >
        <el-form-item label="菜单名称">
        <el-input v-model="form.name" />
        </el-form-item>
        <el-form-item label="上级菜单" prop="parentId">
          <el-tree-select
            v-model="form.parentId"
            :data="rootType"
            check-strictly
            :props="{ label: 'name', value: 'id', children: 'children' }"
            clearable
            placeholder="请选择父分类（可不选）"
          />
        </el-form-item>
        <el-form-item label="菜单路径">
        <el-input v-model="form.path" />
        </el-form-item>
        <el-form-item label="菜单图标">
        <el-input v-model="form.icon" />
        </el-form-item>
        <el-form-item label="是否显示" prop="isShow">
          <el-select v-model="form.isShow" placeholder="请选择">
            <el-option label="显示" :value="0"></el-option>
            <el-option label="隐藏" :value="1"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="组件路径" prop="component">
          <el-input v-model="form.component"/>
        </el-form-item>
    </el-form>
    <template #footer>
        <el-button @click="dialogEditVisible = false">取消</el-button>
        <el-button type="primary" @click="saveUpdateMenus">保存</el-button>
    </template>
    </el-dialog>
</template>
<script setup>

import {toRefs,onBeforeMount,onMounted,reactive,ref,computed} from "vue"
import { ElMessage,ElForm, ElFormItem, ElInput, ElButton,ElMessageBox } from 'element-plus';
import { Plus,Minus } from '@element-plus/icons-vue'
import { getMenusListInfoHandler,addMenusListInfoHandler,updateMenusListInfoHandler,delMenusListInfoHandler } from "../../api/menus.js"
import { base64Decode } from "../../utils/base64.js"
const data = reactive({
    menusData: [{ "name": "", "parentId": "","path":"","icon":"","isShow":"","createdAt":"","updatedAt":""}]
})
const isEditable = ref(false)
const dialogFormVisible = ref(false)
const dialogEditVisible = ref(false)
const {menusData} = toRefs(data)
const formRef = ref(null)

const form = ref({
  id: null,
  name: '',
  parentId: null,
  path: "",
  icon: "",
  isShow: "",
  createdAt: "",
  updatedAt: "",
  component: "",
  children: []
})
// 过滤出主类型，避免选择子类型方法
// function getRootType(treeData) {
//  return treeData
//    .filter(item => Number(item.parent_id) === 0)
//    .map(item => {
//      return {
//        ...item,
//        children: [] // 清空子节点，只显示一级
//      }
//    })
// }
function normalizeTree(data) {
  return data.map(item => {
    return {
      ...item,
      children: item.children ? normalizeTree(item.children) : []
    }
  })
}
const formatIsShow = (row, column, cellValue)=> {
    return cellValue === 0 ? '显示' : '隐藏';
  }
function getRootType(treeData, parentId = 0) {
  return treeData
    .filter(item => Number(item.parentId) === parentId)
    .map(item => {
      return {
        ...item,
        children: getRootType(treeData, item.id) // 递归挂子部门
      }
    })
}
const rootType = computed(() => normalizeTree(menusData.value || []))
const loadConfig = async()=>{
    try {
        const response = await getMenusListInfoHandler()
        if (response?.data?.data) {
            const result = response.data.data;
            const base64String = result.queryData;
            const decodedBytes = atob(base64String);
            const uint8Array = new Uint8Array(decodedBytes.split('').map(c => c.charCodeAt(0)));

            // 使用 setTimeout 将解码和处理放到异步队列中
            setTimeout(() => {
                const decoder = new TextDecoder("utf-8");
                const decodedString = decoder.decode(uint8Array);
                console.log("Decoded string:", decodedString);

                menusData.value = JSON.parse(decodedString);
                console.log("Menus Data:", menusData.value);
            }, 0);  // 延迟 0 毫秒，实际上会在当前事件循环之后执行

        }
    }
    catch(error){
        console.error("获取菜单数据失败:", error)
        ElMessage({
                    message: error?.response?.data?.message || "查询失败------，请重试",
                    type: 'error',
        })
    }
}
const addMenus=()=>{
    form.value = {
      name: '',
      parentId: null,
      path: null,
      icon: null,
      isShow: null,
      component: null,
    }
    dialogFormVisible.value=true
}
const submitForm = async() => {
    try{
        const valid = await formRef.value.validate()
        if(valid){
            console.log('新增分类数据:', form.value)
            const res = await addMenusListInfoHandler(form.value)
            if (res.data) {
                console.log("res.data====20250821",res.data)
                ElMessage({
                message: res.data.message,
                type: 'success'})
            }
            dialogFormVisible.value = false
            await loadConfig()
        }
    } catch(error){
        console.error("添加失败:", error)
        ElMessage({
                    message: error?.response?.data?.message || "添加失败，请重试",
                    type: 'error',
        })
    }
  
}
const removeMenus=async(row)=>{
    try {
        
        await ElMessageBox.confirm(
          `确认要删除【${row.name}】吗？`,
          '删除确认',
          {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning',
          }
        )
        console.log("id=======20250813",row.id)
        const intId = Number(row.id)
        const response = await delMenusListInfoHandler(intId)
        
        if (response.data) {
            ElMessage({
                    message: response.data.message,
                    type: 'success',
            })
            console.log("delcategoryData==========20250821",response.data)
            await loadConfig()
            
        }
    } catch(error) {
        console.error("删除失败:", error)
        ElMessage({
                    message: error?.response?.data?.message || "删除失败，请重试",
                    type: 'error',
        })
        // throw err // 如果需要让调用方知道错误
    }
    
}
const openEditDialog=(row)=>{
    console.log("row======20250813",row)
    form.value={...row}
    dialogEditVisible.value = true
}
const saveUpdateMenus=async()=>{
    try {
        const id=form.value.id
        console.log("==============20250822",id)

        const res = await updateMenusListInfoHandler(id,form.value)
        if (res?.data){
            ElMessage({
                    message: res.data.message,
                    type: 'success',
            })
            console.log("updatetypeData==========20250822",res.data)
            dialogEditVisible.value = false
            await loadConfig()
        }
    }catch(error){
        console.error("更新失败:", error)
        ElMessage({
                    message: error?.response?.data?.message || "更新失败，请重试",
                    type: 'error',
        })
    }
}
onMounted(()=>{
  loadConfig()
})
</script>